<?php

namespace Modules\Book\Controllers;

use Core\Mvc\Controller;
use Core\Mvc\Model\Struct;
use Modules\Book\Models\NodeBook;
use MongoDB\BSON\ObjectID;

class AdminController extends Controller
{

    public function indexAction($book_id)
    {
        $content = array();
        $bookNode = $this->entityManager->get('node', [
            'conditions' => [
                '_id' => new ObjectID($book_id)
            ]
        ]);
        if (!$bookNode) {
            return $this->notFount();
        }
        $bookItem = $this->config->get('book.bookItem');
        $bookItem['_options']['book_id'] = $book_id;
        $bookItemForm = $this->form->create($bookItem);
        if ($bookItemForm->isValid()) {
            $bookItemForm->save();
        }
        $data = NodeBook::findFirst([
            'conditions' => [
                'bid' => $book_id,
            ],
        ]);
        if ($this->request->isPost() && $this->request->hasPost('rh')) {
            $nestable = json_decode($this->request->getPost('rh'));
            $nestable = jsonToHierarchy($nestable);
            //print_r($rh);
            $toc = Struct::nestableSort($nestable, $data->toc);
            //$this->config->printCode($toc);
            if ($toc !== false) {
                $data->toc = $toc;
                if ($data->save()) {
                    $this->flash->success('菜单排序成功');
                } else {
                    $this->flashSession->success('菜单排序保存失败');
                }
                $data = NodeBook::findFirst([
                    'conditions' => [
                        'bid' => $book_id,
                    ],
                ]);
            }
        }

        self::$variables += array(
            'title' => '排序书本目录',
            'description' => '书本：《' . $bookNode->getTitle() . '》',
            '#templates' => 'page',
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'nodeList' => array(
                    'href' => array(
                        'for' => 'adminEntityList',
                        'entity' => 'node',
                        'page' => 1,
                    ),
                    'name' => '内容列表',
                ),
            ),
            'content' => array(),
        );
        // 添加编辑菜单
        $content['bookList'] = array(
            '#templates' => 'box',
            'title' => '目录列表',
            'max' => false,
            'wrapper' => true,
            'color' => 'primary',
            'size' => '6',
            'content' => array(
                '#templates' => 'adminBookList',
                'id' => 'BookListHierarchy',
                'title_display' => false,
                'data' => $data,
            ),
        );
        $content['termHandle'] = array(
            '#templates' => 'box',
            'title' => '添加项目',
            'max' => false,
            'id' => 'right_handle',
            'wrapper' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'termForm' => $bookItemForm->renderForm(),
            ),
        );

        self::$variables['content'] += $content;
    }

    public function editAction($book_id, $id)
    {
        $nodeBook = NodeBook::findFirst([
            'conditions' => [
                'bid' => $book_id,
            ],
        ]);
        if (!$nodeBook) {
            return $this->notFount();
        }
        $struct = new Struct($nodeBook->toc);
        $data = $struct->get($id);
        if (!$data) {
            return $this->notFount();
        }
        $data['id'] = $id;
        $bookItem = $this->config->get('book.bookItem');
        $bookItem['_options']['book_id'] = $book_id;
        $bookItem = $this->form->create($bookItem, $data);
        if ($bookItem->isValid()) {
            $bookItem->save();
            return $this->moved([
                'for' => 'adminBookTocSort',
                'book_id' => $book_id
            ]);
        }
        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'content' => array(
                'termEditorForm' => array(
                    '#templates' => 'box',
                    'wrapper' => false,
                    'title' => '书本项目编辑-',
                    'max' => false,
                    'color' => 'success',
                    'size' => '12',
                    'content' => array(
                        'data' => $bookItem->renderForm(),
                    ),
                ),
            ),
        );
    }

    public function deleteAction($book_id, $id)
    {
        $nodeBook = NodeBook::findFirst([
            'conditions' => [
                'bid' => $book_id,
            ],
        ]);
        if (!$nodeBook) {
            $this->flashSession->error('删除失败,数据不存在');
            return $this->moved();
        }
        $struct = new Struct($nodeBook->toc);
        $struct->delete($id);
        $toc = $struct->getData();
        $nodeBook->toc = $toc;
        if ($nodeBook->save()) {
            $nodeData = $this->entityManager->get('node', [
                'conditions' => [
                    '_id' => new ObjectID($id)
                ]
            ]);
            if ($nodeData) {
                $nodeData->book_id = 'null';
                $nodeData->save();
            }
            $this->flashSession->success('删除成功');
        } else {
            $this->flashSession->error('更改后的数据保存失败');
        }
        return $this->moved(['for' => 'adminBookTocSort', 'book_id' => $book_id]);
    }
}
